import { Logger } from '@nestjs/common';
import { OnGatewayInit, SubscribeMessage, WebSocketGateway, WebSocketServer } from '@nestjs/websockets';
import { Socket } from 'socket.io';

const opt2 = {
  path: '/chat2',
  allowEIO3: true,
  cors: {
    origin: /.*/,
    credentials: true
  }
};

@WebSocketGateway(opt2)
export class Chat2Gateway implements OnGatewayInit {
  private logger: Logger = new Logger('Chat1Gateway');

  @WebSocketServer()
  server: any;

  afterInit(server: any) {
    this.server = server;
  }

  @SubscribeMessage('join')
  onJoin(socket: Socket, payload: any): any {
    socket.join(payload.room);
    this.server.to(payload.room).emit('allMsg', payload);
  }

  @SubscribeMessage('message')
  handleMessage(client: any, payload: any): any {
    return {
      event: 'message',
      data: { code: 1, msg: "[chat2]服务 https://an.rustfisher.com" }
    };
  }

  @SubscribeMessage('m2s')
  onChatMsg(client: any, payload: any): any {
    this.logger.log(payload);
    var uid: String = payload.uid;
    var roomId = payload.room;
    if (uid != null && uid.length > 0) {
      this.server.to(roomId).emit('allMsg', payload);
    } else {
      this.logger.warn('[m2s] 用户输入uid无效');
    }
  }
}
